<?php
    function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }

    $id= 'XD16UrrsFdU6DdSq';//'6MKOqxGiGU4AUk44';
    $key= '7YFCfcjqLs8Jy5TcKRC2S3OFRYDiPz';
    $host = 'http://habitphoto.oss-cn-shenzhen.aliyuncs.com'; //'http://post-test.oss-cn-hangzhou.aliyuncs.com';

    $now = time();
    $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
    $end = $now + $expire;
    $expiration = gmt_iso8601($end);

    $dir = 'sss/';

    //最大文件大小.用户可以自己设置
    $condition = array(0=>'content-length-range', 1=>0, 2=>4024000);

    //$policy = '{"expiration": "2120-01-01T12:00:00.000Z","conditions":[{"bucket": "ioutsider" },["content-length-range", 0, 104857600]]}';
    $conditions[] = $condition; 

    //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
    $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
    $conditions[] = $start; 


    $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
    //echo json_encode($arr);
    //return;
    $policy = json_encode($arr);
    $base64_policy = base64_encode($policy);
    $string_to_sign = $base64_policy;
    $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

    $response = array();
    $response['accessid'] = $id;
    $response['host'] = $host;
    $response['policy'] = $base64_policy;
    $response['signature'] = $signature;
    $response['expire'] = $end;
    //这个参数是设置用户上传指定的前缀
    $response['dir'] = $dir;
    //echo json_encode($response);
?>

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>文件上传</div>
        <form action="<?php echo $response['host'];?>" method="post" enctype="multipart/form-data">
            <label for="file">选择文件:</label>
            <input type="hidden" name="OSSAccessKeyId" id="OSSAccessKeyId"  value="<?php echo $response['accessid'] ?>" />
            <input type="hidden" name="policy" id="policy"  value='<?php echo $response['policy'] ?>' />
            <input type="hidden" name="signature" id="signature"  value="<?php echo $response['signature'] ?>" />
            <input type="hidden" name="key" id="key"  value="<?php echo $response['dir'] ?>${filename}" />
            <input type="file" name="file" id="file" />
            <br />
            <input type="submit" name="submit" value="确定" />
        </form>
    </body>
</html>